//
//  PurchaserOrderViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/7/12.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "PurchaserOrderViewController.h"
#import "PurchaseOrderContentViewController.h"

#define leftMargin jisuan(80)
#define labelMargin jisuan(78)

@interface PurchaserOrderViewController ()<UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *titleScrollView;
@property (strong, nonatomic) UIView *sliderView;
@property (strong, nonatomic) UIScrollView *contentScrollView;

@property (assign, nonatomic) CGFloat labelTotolWidth;

@property (strong, nonatomic) NSArray *arr;

@property (strong, nonatomic) NSMutableArray *labelArr;
@property (strong, nonatomic) NSMutableArray *labelxArr;


@end

@implementation PurchaserOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WhiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    
    self.title = @"我的进货订单";
    
    self.labelArr = [NSMutableArray array];
    self.labelxArr = [NSMutableArray array];
    
    [self.view addSubview:self.titleScrollView];
    [self.view addSubview:self.contentScrollView];
    
    __weak typeof(self) weakSelf = self;
    [self.titleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.view.mas_top);
        make.height.mas_equalTo(jisuan(86));
        
    }];
    [self.contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.titleScrollView.mas_bottom);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
        
    }];
    

    
    [self setupTitleScrollView];
    [self addChildVCs];
    
    [self.view layoutIfNeeded];
    
    [self setDefaultTitleAndChildVC];
    
}

- (void)setDefaultTitleAndChildVC {
    
    UILabel *defaultLabel = self.labelArr[self.type];
    defaultLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(24)];
    
    [self.titleScrollView addSubview:self.sliderView];
    UILabel *label = self.titleScrollView.subviews[self.type];
    self.sliderView.frame = CGRectMake([self.labelxArr[self.type] floatValue], jisuan(78), label.width, jisuan(6));

    PurchaseOrderContentViewController *vc = self.childViewControllers[self.type];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
//    vc.view.frame = self.contentScrollView.bounds;
    vc.view.frame = CGRectMake(WIDTH * self.type, 0, WIDTH, self.contentScrollView.height);
    self.contentScrollView.contentOffset = CGPointMake(WIDTH * self.type, 0);
    [self.contentScrollView addSubview:vc.view];

}

#pragma mark -label点击事件
- (void)labelGestureClick:(UIGestureRecognizer *)recognizer {
    
    NSLog(@"label点击事件");
    
    UILabel *label = (UILabel *)recognizer.view;
    
    CGFloat contentSetOffx = label.tag * WIDTH;
    
    [self.contentScrollView setContentOffset:CGPointMake(contentSetOffx, 0) animated:YES];
    
    [self isHidden:contentSetOffx];

    for (int i = 0 ; i < self.childViewControllers.count; i ++) {
        
        UILabel *temp = self.titleScrollView.subviews[i] ;
        
        temp.font = Font(20);
        
    }
    
    label.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(24)];

    CGFloat x = [self.labelxArr[label.tag] floatValue];
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
      
        CGRect rect = weakSelf.sliderView.frame;
        rect.origin.x = x;
        rect.size.width = label.width;
        weakSelf.sliderView.frame = rect;
    
    }];
    
}

- (void)isHidden:(CGFloat)offsetX {
    
    NSInteger index = (NSInteger)offsetX / WIDTH;
    
    if (index == 1) {
        
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [button setTitle:@"管理" forState:(UIControlStateNormal)];
        [button setTitleColor:Color333333 forState:(UIControlStateNormal)];
        button.titleLabel.font = Font(24);
        button.frame = CGRectMake(0, 0, 50, 20);
        
        [button addTarget:self action:@selector(manager:) forControlEvents:(UIControlEventTouchUpInside)];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        
        
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    }else {
        
        self.navigationItem.rightBarButtonItem = nil;
    }
    
}

#pragma mark -管理点击事件
- (void)manager:(UIButton *)btn {
    
    PurchaseOrderContentViewController *vc = self.childViewControllers[1];
    
    if ([btn.titleLabel.text isEqualToString:@"管理"]) {
        //移除之前选中的内容
//        if (self.selectorPatnArray.count > 0) {
//            [self.selectorPatnArray removeAllObjects];
//        }
        [btn setTitle:@"完成" forState:(UIControlStateNormal)];
        [vc isHiddenSelectedView:NO];
        
        //进入编辑状态
        [vc.gooodsTableView setEditing:YES animated:YES];
        
    }else{
        
        [btn setTitle:@"管理" forState:(UIControlStateNormal)];
        [vc isHiddenSelectedView:YES];
        　　　　　//对选中内容进行操作
//        NSLog(@"选中个数是 : %lu   内容为 : %@",(unsigned long)self.selectorPatnArray.count,self.selectorPatnArray);
        //取消编辑状态
        [vc.gooodsTableView setEditing:NO animated:YES];
        
    }
    
    
    
    
}

#pragma mark -delegate
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    NSInteger index = scrollView.contentOffset.x / WIDTH;
    
    PurchaseOrderContentViewController *vc = self.childViewControllers[index];
    UILabel *label = self.titleScrollView.subviews[index];
    
    for (int i = 0; i < self.labelArr.count;  i ++) {
        
        UILabel *temp = self.labelArr[i];
        temp.font = Font(20);
    }
    
    label.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(24)];;
    
    CGFloat width = self.titleScrollView.frame.size.width;
    CGFloat offsetX = label.center.x - width * 0.5;
    // 最大偏移量
    CGFloat maxOffsetx = self.titleScrollView.contentSize.width - width;
    if (offsetX < 0) {
        offsetX = 0;
    } else if (offsetX > maxOffsetx) {
        offsetX = maxOffsetx;
    }

    [self.titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:NO];
    
    // 如果子控制器的view已经在上面,就直接返回
    if (vc.view.superview) {
        [vc.view removeFromSuperview];
    }
    
    // 添加
    CGFloat vcW = scrollView.frame.size.width;
    CGFloat vcH = scrollView.frame.size.height;
    CGFloat vcY = 0;
    CGFloat vcX = index * vcW;
    vc.view.frame = CGRectMake(vcX, vcY, vcW, vcH);
    [scrollView addSubview:vc.view];

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    
    CGFloat scale = scrollView.contentOffset.x / WIDTH;
  
    NSInteger index = (int)scale;
    
    [self isHidden:scrollView.contentOffset.x];

    UILabel *temp = self.titleScrollView.subviews[index];
    
    CGFloat x = (temp.width + jisuan(78) + jisuan(16)) * scale + jisuan(80);

    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3
                     animations:^{
    
                         CGRect rect = weakSelf.sliderView.frame;
                         rect.origin.x = x;
                         rect.size.width = temp.width;
                         weakSelf.sliderView.frame = rect;
                         
                     }];

}

/**
 *  当scrollview停止滚动时调用这个方法 (用户手动触发的动画结束,会调用这个方法)
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}


#pragma mark -分类标题scrollview布局
- (void)setupTitleScrollView {

    self.labelTotolWidth = leftMargin;
    
    for (int i = 0; i < self.arr.count; i ++) {
        
        UILabel *label = [[UILabel alloc] init];
        label.tag = i;
        label.userInteractionEnabled = YES;
        label.text = self.arr[i];
        label.font = Font(20);
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = Color333333;
        [label sizeToFit];

        [self.labelArr addObject:label];
        
        if (i == 0) {

        }else {
            
            UILabel *tempL = self.labelArr[i - 1];
            CGFloat width = tempL.size.width + jisuan(16);
            self.labelTotolWidth = self.labelTotolWidth + width+ labelMargin;
            
        }
        
        [self.labelxArr addObject:[NSString stringWithFormat:@"%.2f",self.labelTotolWidth]];
        
        label.frame = CGRectMake(self.labelTotolWidth, 0, label.size.width + jisuan(16), jisuan(100));
        [self.titleScrollView insertSubview:label atIndex:i];
        
        UITapGestureRecognizer *labelGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelGestureClick:)];
        [label addGestureRecognizer:labelGesture];
    
    }
    
    
    UILabel *temp = [self.labelArr lastObject];
    CGFloat scrollviewWith = self.labelTotolWidth + leftMargin + temp.width;
    
    CGSize size = CGSizeMake(scrollviewWith, 0);
    self.titleScrollView.contentSize = size;
    
//    UILabel *firstL = self.labelArr.firstObject;
//    firstL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(24)];
//
//    UILabel *temp = [self.labelArr lastObject];
//    CGFloat scrollviewWith = self.labelTotolWidth + leftMargin + temp.width;
//
//    CGSize size = CGSizeMake(scrollviewWith, 0);
//    self.titleScrollView.contentSize = size;
//
//    [self.titleScrollView addSubview:self.sliderView];
//    UILabel *label = [self.titleScrollView.subviews firstObject];
//    self.sliderView.frame = CGRectMake([self.labelxArr.firstObject floatValue], jisuan(78), label.width, jisuan(6));
    
}

#pragma mark -添加自控制器
- (void)addChildVCs {

    for (int i = 0; i < self.labelArr.count; i ++) {
        
        PurchaseOrderContentViewController *contentVC = [[PurchaseOrderContentViewController alloc] init];
        
        contentVC.tradeType = i;
        
        [self addChildViewController:contentVC];
    
    }
    
    
    self.contentScrollView.contentSize = CGSizeMake(WIDTH * self.childViewControllers.count, 0);
    
//    PurchaseOrderContentViewController *vc = self.childViewControllers.firstObject;
//
//    self.automaticallyAdjustsScrollViewInsets = NO;
//    vc.view.frame = self.contentScrollView.bounds;
//    [self.contentScrollView addSubview:vc.view];
//
//    self.contentScrollView.contentSize = CGSizeMake(WIDTH * self.childViewControllers.count, 0);
    
}

#pragma mark -lazy
- (UIScrollView *)titleScrollView {
    
    if (!_titleScrollView) {
        
        _titleScrollView = [[UIScrollView alloc] init];
        _titleScrollView.backgroundColor = WhiteColor;
        
        _titleScrollView.showsVerticalScrollIndicator = NO;
        _titleScrollView.showsHorizontalScrollIndicator = NO;
        
        
        if (@available(iOS 11.0, *)) {
            
            _titleScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    
    return _titleScrollView;
}

- (UIView *)sliderView {
    
    if (!_sliderView) {
        
        _sliderView = [[UIView alloc] init];
        _sliderView.backgroundColor = Colorff0000;
        
    }
    
    return _sliderView;
}



- (UIScrollView *)contentScrollView {
    
    if (!_contentScrollView) {
        
        _contentScrollView = [[UIScrollView alloc] init];
        _contentScrollView.backgroundColor = WhiteColor;
        
        _contentScrollView.delegate = self;
        _contentScrollView.bounces = NO;
        _contentScrollView.pagingEnabled = YES;
        
        _contentScrollView.showsHorizontalScrollIndicator = NO;
        _contentScrollView.showsVerticalScrollIndicator = NO;
        
        if (@available(iOS 11.0, *)) {
            
            _contentScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        
    }
    
    return _contentScrollView;
}

- (NSArray *)arr {
    
    if (!_arr) {
        
        _arr = @[ @"待支付", @"已进货", @"已返利", @"已分红"];
   
    }
    
    return _arr;
}

#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

    self.navigationController.navigationBar.hidden = NO;
//    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
//    self.navigationController.navigationBar.hidden = NO;
//    self.tabBarController.tabBar.hidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
